package com.jumi.microservice.service.taobao;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.common.constant.DelFlag;
import com.jumi.microservice.common.page.TableDataInfo;
import com.jumi.microservice.config.TaoBaoConfig;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.dto.taobao.*;
import com.jumi.microservice.entity.UserCoupon;
import com.jumi.microservice.mapper.UserCouponMapper;
import com.jumi.microservice.service.ITaoBaoService;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.*;
import com.taobao.api.response.*;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Dirk
 * @Date 2021-01-08 08:50
 */
@DubboService
public class TaoBaoServiceImpl implements ITaoBaoService {

    private static final Logger log = LoggerFactory.getLogger(TaoBaoServiceImpl.class);

    @Resource
    private TaoBaoConfig taoBaoConfig;

    @Resource
    private UserCouponMapper userCouponMapper;

    @Override
    public Long getSpecialId(String sessionKey) {
        log.info("accessToken:[{}]", sessionKey);
        TaobaoClient client = new DefaultTaobaoClient(taoBaoConfig.getUrl(), taoBaoConfig.getAppkey(), taoBaoConfig.getSecret());
        TbkScPublisherInfoSaveRequest tbkScPublisherInfoSaveRequest = new TbkScPublisherInfoSaveRequest();
        tbkScPublisherInfoSaveRequest.setInviterCode(taoBaoConfig.getInviterCode());
        tbkScPublisherInfoSaveRequest.setInfoType(1L);
        TbkScPublisherInfoSaveResponse tbkScPublisherInfoSaveResponse = null;
        try {
            tbkScPublisherInfoSaveResponse = client.execute(tbkScPublisherInfoSaveRequest, sessionKey);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if (ObjectUtils.isEmpty(tbkScPublisherInfoSaveResponse)) {
            throw new BaseException(500, "授权绑定失败");
        }
        log.info("私域用户备案返回值:[{}]", JSON.toJSONString(tbkScPublisherInfoSaveResponse.getData()));
        return tbkScPublisherInfoSaveResponse.getData().getSpecialId();
    }

    @Override
    public Boolean oauth(OauthRequest oauthRequest) {
        Long specialId = getSpecialId(oauthRequest.getSessionKey());
        QueryWrapper<UserCoupon> userCouponQw = new QueryWrapper<>();
        userCouponQw.eq("tb_special_id", oauthRequest.getUid());
        UserCoupon userCoupon = userCouponMapper.selectOne(userCouponQw);
        if (!ObjectUtils.isEmpty(userCoupon) && !userCoupon.getUid().equals(oauthRequest.getUid())) {
            throw new BaseException(500, "该淘宝账号已绑定其他用户");
        }

        userCouponQw = new QueryWrapper<>();
        userCouponQw.eq("uid", oauthRequest.getUid());
        userCoupon = userCouponMapper.selectOne(userCouponQw);
        if (!ObjectUtils.isEmpty(userCoupon)) {
            if (!ObjectUtils.isEmpty(userCoupon.getTbSpecialId())) {
                return true;
            }
            userCoupon.setTbSpecialId(specialId);
            return userCouponMapper.updateById(userCoupon) > 0;
        }
        userCoupon = new UserCoupon();
        userCoupon.setUid(oauthRequest.getUid());
        userCoupon.setTbSpecialId(specialId);
        return userCouponMapper.insert(userCoupon) > 0;
    }

    @Override
    public Boolean oauthH5(OauthRequest oauthRequest) {
        TaobaoClient client = new DefaultTaobaoClient(taoBaoConfig.getUrl(), taoBaoConfig.getAppkey(), taoBaoConfig.getSecret());
        TopAuthTokenCreateRequest topAuthTokenCreateRequest = new TopAuthTokenCreateRequest();
        topAuthTokenCreateRequest.setCode(oauthRequest.getCode());
        TopAuthTokenCreateResponse topAuthTokenCreateResponse = null;
        try {
            topAuthTokenCreateResponse = client.execute(topAuthTokenCreateRequest);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if (ObjectUtils.isEmpty(topAuthTokenCreateResponse)) {
            return false;
        }
        log.info("授权返回值：[{}]", topAuthTokenCreateResponse.getTokenResult());
        String sessionKey = JSON.parseObject(topAuthTokenCreateResponse.getTokenResult()).getString("access_token");
        oauthRequest.setSessionKey(sessionKey);
        oauthRequest.setUid(oauthRequest.getUid());
        return oauth(oauthRequest);
    }

    @Override
    public List<FavoritesResponse> getFavorites() {
        TaobaoClient client = new DefaultTaobaoClient(taoBaoConfig.getUrl(), taoBaoConfig.getAppkey(), taoBaoConfig.getSecret());
        TbkDgOptimusMaterialRequest tbkDgOptimusMaterialRequest = new TbkDgOptimusMaterialRequest();
        tbkDgOptimusMaterialRequest.setAdzoneId(Long.valueOf(taoBaoConfig.getPid()));
        tbkDgOptimusMaterialRequest.setMaterialId(31519L);
        TbkDgOptimusMaterialResponse tbkDgOptimusMaterialResponse = null;
        try {
            tbkDgOptimusMaterialResponse = client.execute(tbkDgOptimusMaterialRequest);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if (ObjectUtils.isEmpty(tbkDgOptimusMaterialResponse)) {
            return new ArrayList<>();
        }
        List<TbkDgOptimusMaterialResponse.FavoritesDetail> favoritesDetailList =
                tbkDgOptimusMaterialResponse.getResultList().get(0).getFavoritesInfo().getFavoritesList();
        List<FavoritesResponse> favoritesResponseList = new ArrayList<>();
        favoritesDetailList.forEach(favoritesDetail -> {
            FavoritesResponse response = new FavoritesResponse();
            BeanUtils.copyProperties(favoritesDetail, response);
            favoritesResponseList.add(response);
        });
        return favoritesResponseList;
    }

    @Override
    @Cacheable(value = "TaoBao:getMaterial()",
            key = "#materialRequest.materialEnum + '-' + #materialRequest.favoritesId + '-' + #materialRequest.pageNum")
    public TableDataInfo<MaterialResponse> getMaterial(MaterialRequest materialRequest) {
        TableDataInfo<MaterialResponse> result = new TableDataInfo<>();
        TaobaoClient client = new DefaultTaobaoClient(taoBaoConfig.getUrl(), taoBaoConfig.getAppkey(), taoBaoConfig.getSecret());
        TbkDgOptimusMaterialRequest tbkDgOptimusMaterialRequest = new TbkDgOptimusMaterialRequest();
        tbkDgOptimusMaterialRequest.setPageNo(materialRequest.getPageNum().longValue());
        tbkDgOptimusMaterialRequest.setPageSize(materialRequest.getPageSize().longValue());
        tbkDgOptimusMaterialRequest.setAdzoneId(Long.valueOf(taoBaoConfig.getPid()));
        tbkDgOptimusMaterialRequest.setMaterialId(materialRequest.getMaterialEnum().getCode());
        tbkDgOptimusMaterialRequest.setFavoritesId(materialRequest.getFavoritesId());
        TbkDgOptimusMaterialResponse tbkDgOptimusMaterialResponse = null;
        try {
            tbkDgOptimusMaterialResponse = client.execute(tbkDgOptimusMaterialRequest);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if (tbkDgOptimusMaterialResponse == null || tbkDgOptimusMaterialResponse.getResultList() == null) {
            result.setRows(new ArrayList<>());
            return result;
        }
        log.info("淘宝物料精选接口返回值：[{}]", JSON.toJSONString(tbkDgOptimusMaterialResponse));
        List<MaterialResponse> responseList = new ArrayList<>();
        tbkDgOptimusMaterialResponse.getResultList().forEach(mapData -> {
            MaterialResponse materialResponse = new MaterialResponse();
            BeanUtils.copyProperties(mapData, materialResponse);
            // 统一反佣比例单位
            BigDecimal commission = new BigDecimal(materialResponse.getCommissionRate())
                    .divide(new BigDecimal("100"), 4, RoundingMode.HALF_DOWN);
            materialResponse.setCommissionRate(commission.toString());
            responseList.add(materialResponse);
        });
        result.setRows(responseList);
        Long total = tbkDgOptimusMaterialResponse.getTotalCount();
        result.setTotal(total != null ? total : 0);
        return result;
    }

    @Override
    public TableDataInfo<MaterialResponse> searchMaterial(SearchRequest searchRequest) {
        if (ObjectUtils.isEmpty(searchRequest.getItemCats()) && ObjectUtils.isEmpty(searchRequest.getKeyword())) {
            throw new BaseException(500, "搜索内容不能为空！");
        }
        TableDataInfo<MaterialResponse> result = new TableDataInfo<>();
        TaobaoClient client = new DefaultTaobaoClient(taoBaoConfig.getUrl(), taoBaoConfig.getAppkey(), taoBaoConfig.getSecret());
        TbkDgMaterialOptionalRequest tbkDgMaterialOptionalRequest = new TbkDgMaterialOptionalRequest();
        tbkDgMaterialOptionalRequest.setPageSize(searchRequest.getPageSize().longValue());
        tbkDgMaterialOptionalRequest.setPageNo(searchRequest.getPageNum().longValue());
        tbkDgMaterialOptionalRequest.setPlatform(2L);
        tbkDgMaterialOptionalRequest.setCat(searchRequest.getItemCats());
        tbkDgMaterialOptionalRequest.setQ(searchRequest.getKeyword());
        tbkDgMaterialOptionalRequest.setAdzoneId(Long.valueOf(taoBaoConfig.getPid()));
        tbkDgMaterialOptionalRequest.setSort(searchRequest.getSort());
        tbkDgMaterialOptionalRequest.setHasCoupon(searchRequest.getHasCoupon());
        tbkDgMaterialOptionalRequest.setNeedFreeShipment(searchRequest.getNeedFreeShipment());
        TbkDgMaterialOptionalResponse tbkDgMaterialOptionalResponse = null;
        try {
            tbkDgMaterialOptionalResponse = client.execute(tbkDgMaterialOptionalRequest);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if (tbkDgMaterialOptionalResponse == null) {
            result.setRows(new ArrayList<>());
            return result;
        }
        if (!ObjectUtils.isEmpty(tbkDgMaterialOptionalResponse.getErrorCode())) {
            throw new BaseException(500, tbkDgMaterialOptionalResponse.getSubMsg());
        }
        List<MaterialResponse> materialResponseList = new ArrayList<>();
        tbkDgMaterialOptionalResponse.getResultList().forEach(mapData -> {
            MaterialResponse materialResponse = new MaterialResponse();
            BeanUtils.copyProperties(mapData, materialResponse);
            // 统一反佣比例单位
            BigDecimal commission = new BigDecimal(materialResponse.getCommissionRate())
                    .divide(new BigDecimal("10000"), 4, RoundingMode.HALF_DOWN);
            materialResponse.setCommissionRate(commission.toString());
            materialResponse.setCouponAmount(ObjectUtils.isEmpty(mapData.getCouponAmount()) ?
                    0L : Long.parseLong(mapData.getCouponAmount()));
            materialResponseList.add(materialResponse);
        });
        result.setRows(materialResponseList);
        result.setTotal(tbkDgMaterialOptionalResponse.getTotalResults());
        return result;

    }

    @Override
    public ItemInfoResponse getItemInfo(ItemInfoRequest itemInfoRequest) {
        TaobaoClient client = new DefaultTaobaoClient(taoBaoConfig.getUrl(), taoBaoConfig.getAppkey(), taoBaoConfig.getSecret());
        TbkItemInfoGetRequest tbkItemInfoGetRequest = new TbkItemInfoGetRequest();
        tbkItemInfoGetRequest.setNumIids(itemInfoRequest.getItemId().toString());
        tbkItemInfoGetRequest.setPlatform(itemInfoRequest.getPlatform());
        TbkItemInfoGetResponse tbkItemInfoGetResponse = null;
        try {
            tbkItemInfoGetResponse = client.execute(tbkItemInfoGetRequest);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        ItemInfoResponse response = new ItemInfoResponse();
        if (ObjectUtils.isEmpty(tbkItemInfoGetResponse)) {
            return response;
        }
        log.info(JSON.toJSONString(tbkItemInfoGetResponse.getResults()));
        BeanUtils.copyProperties(tbkItemInfoGetResponse.getResults().get(0), response);
        return response;
    }

    @Override
    public Long getUserTbSpecialId(Long uid) {
        QueryWrapper<UserCoupon> userCouponQw = new QueryWrapper<>();
        userCouponQw.eq("uid", uid);
        userCouponQw.eq("del_flag", DelFlag.NORMAL);
        UserCoupon userCoupon = userCouponMapper.selectOne(userCouponQw);
        if (!ObjectUtils.isEmpty(userCoupon) && !ObjectUtils.isEmpty(userCoupon.getTbSpecialId())) {
            return userCoupon.getTbSpecialId();
        }
        return 0L;
    }

    @Override
    public PwdResponse createPwd(PwdRequest pwdRequest) {
        TaobaoClient client = new DefaultTaobaoClient(taoBaoConfig.getUrl(), taoBaoConfig.getAppkey(), taoBaoConfig.getSecret());
        TbkTpwdCreateRequest tbkTpwdCreateRequest = new TbkTpwdCreateRequest();
        tbkTpwdCreateRequest.setText(pwdRequest.getText());
        tbkTpwdCreateRequest.setUrl(pwdRequest.getUrl());
        TbkTpwdCreateResponse tbkTpwdCreateResponse = null;
        try {
            tbkTpwdCreateResponse = client.execute(tbkTpwdCreateRequest);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        PwdResponse pwdResponse = new PwdResponse();
        if (ObjectUtils.isEmpty(tbkTpwdCreateResponse)) {
            return pwdResponse;
        }
        BeanUtils.copyProperties(tbkTpwdCreateResponse, pwdResponse);
        return pwdResponse;
    }
}
